<script setup lang="ts">
import {
  getCurrentInstance,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import CommonBaseInfoTable from '@/views/project-update/month-report/common-base-info-table.vue'
import { queryArea, uploadFile } from '@/api/question'
import DrawMap from '@/components/draw-map/index.vue'
import { getProjectInventoryDetail } from '@/api/project-update/project-inventory'
import { Message } from 'element-ui'
import {
  getAreaStorageList,
  getAreaStoragePassList,
} from '@/api/project-update/area-storage'
import { baseFileUrl } from '@/utils'

const vm = getCurrentInstance()

const props = defineProps({
  userLevel: Number,
  pkid: String,
  disabled: Boolean,
})

const regionList = ref([])
const regionId = ref('')

const streetId = ref('')
const streetList = ref([])

const getAreaInfo = async () => {
  try {
    const res = await queryArea({})
    if (res.success) {
      regionList.value = res.data[0].children
      const user = JSON.parse(localStorage.getItem('user') || '{}')?.user
      if (props.userLevel === 2) {
        regionId.value = user.refId
      }
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error(error)
  }
}

watch(
  () => regionId.value,
  (val) => {
    streetId.value = ''
    if (val) {
      streetList.value =
        regionList.value.find((item) => item.pkid === val)?.children || []
    } else {
      streetList.value = []
    }
  }
)

const getRegionName = (id: string) => {
  return regionList.value.find((item) => item.pkid === id)?.areaName || ''
}

const getStreetName = (ids: string[]) => {
  return streetList.value
    .filter((item) => ids.includes(item.pkid))
    .map((item) => item.areaName)
    .join(',')
}

const form = reactive({
  fileRelList: [],
})

const areaProjectOptions = ref([])

const getAreaProjectOptions = async () => {
  try {
    const res = await getAreaStoragePassList({})
    if (res.success) {
      areaProjectOptions.value =
        res.data?.map((item) => ({
          label: item.regionName,
          value: item.id,
          regionBeforeRatio: item.regionBeforeRatio,
          regionAfterRatio: item.regionAfterRatio,
        })) || []
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error(error)
  }
}

const projectBasePart = ref([
  {
    label: '项目名称',
    key: 'peName',
    renderType: 'input',
    placeholder: '请输入',
    labelClass: 'required-label',
  },
  {
    label: '所属片区项目',
    key: 'regionId',
    renderType: 'select',
    calc: true,
    options: areaProjectOptions,
  },
  {
    label: '入库批次',
    key: 'batch',
    labelClass: 'required-label',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '项目所属阶段',
    key: 'peStage',
    labelClass: 'required-label',
    renderType: 'radio',
    options: [
      { label: '储备阶段', value: 'reserve' },
      { label: '实施阶段', value: 'implement' },
      { label: '运营阶段', value: 'manage' },
    ],
  },
  {
    label: '开工时间',
    key: 'startTime',
    renderType: 'year',
  },
  {
    label: '完工时间',
    key: 'endTime',
    renderType: 'year',
  },
  {
    label: '项目周期',
    key: 'peCycle',
    renderType: 'calc',
    calcFields: ['startTime', 'endTime'],
  },
  {
    label: '项目位置',
    key: 'pePosition',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const projectBasePart2 = ref([
  {
    label: '位置范围',
    labelClass: 'required-label',
    key: 'locationRange',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '项目类型（可多选）',
    key: 'peType',
    labelClass: 'required-label',
    renderType: 'checkbox',
    calc: true,
    options: [
      { label: '老旧小区（街区）', value: '01' },
      { label: '老旧商业区', value: '02' },
      { label: '老旧厂区', value: '03' },
      { label: '历史文化区', value: '04' },
      { label: '公共空间', value: '05' },
      { label: '其他', value: '10', input: true, otherKey: 'other1' },
    ],
  },
  {
    label: '前期业主或实施主体企业',
    key: 'owner',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '技术方案编制单位（策划实施单位）',
    key: 'planCompany',
    renderType: 'input',
    placeholder: '请输入',
    labelClass: 'required-label',
  },
])

const projectBasePart3 = ref([
  {
    label: '项目实施单位',
    key: 'buildCompany',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '项目运营单位',
    key: 'operateCompany',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const projectBasePart4 = ref([
  {
    label: '更新总体目标/更新内容',
    key: 'updateContent',
    renderType: 'textarea',
  },
  {
    label: '更新纬度',
    key: 'latitude',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '生活功能',
    key: 'lifeFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '生态功能',
    key: 'ecologicalFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '产业功能',
    key: 'industryFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '文化功能',
    key: 'cultureFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '安全功能',
    key: 'securityFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '交通功能',
    key: 'trafficFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '其他',
    key: 'other',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '项目更新指标',
    key: 'targetIndex',
    renderType: 'render',
    contentClass: 'no-padding-content project-update-index',
  },
  {
    label: '片区更新指标',
    key: 'areaTargetIndex',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '资金来源',
    key: 'fundingSource',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '项目涵盖',
    key: 'projectCover',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '合作模式',
    key: 'cooperateMode',
    renderType: 'radio',
    options: [
      { label: '政府主导', value: '01' },
      { label: '市场主导', value: '02' },
      { label: '合作', value: '03' },
    ],
  },
  {
    label: '建设运营模式（可多选）',
    key: 'operateMode',
    renderType: 'checkbox',
    options: [
      { label: '平台公司自建自营', value: '01' },
      { label: '平台公司自建+委托运营', value: '02' },
      { label: '引入社会企业建设运营', value: '03' },
      { label: 'PPP模式', value: '04' },
      { label: 'EPC模式', value: '05' },
      { label: 'EPC+O模式', value: '06' },
      { label: '其他模式', value: '10' },
    ],
  },
  {
    label: '控规调整',
    key: 'planningAdjustment',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '房屋征迁',
    key: 'houseDemolition',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '土地供应',
    key: 'landSupply',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '历史资源保护利用',
    key: 'historicalResource',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '古树名木',
    key: 'ancientTree',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '项目矢量信息',
    key: 'projectVector',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '项目实施计划',
    key: 'implementationPlan',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
])

const locationRangeTableProps = ref([
  {
    label: '所属区县',
    key: 'district',
    renderType: 'render',
  },
  {
    label: '所属街道',
    key: 'street',
    renderType: 'render',
  },
  {
    label: '东至',
    key: 'east',
    renderType: 'input',
  },
  {
    label: '南至',
    key: 'south',
    renderType: 'input',
  },
  {
    label: '西至',
    key: 'west',
    renderType: 'input',
  },
  {
    label: '北至',
    key: 'north',
    renderType: 'input',
  },
  {
    label: '总占地面积（公顷）',
    key: 'area',
    renderType: 'input',
  },
])

const ownerTableProps = ref([
  {
    label: '单位名称',
    key: 'companyName',
    renderType: 'input',
    placeholder: '请输入',
    labelClass: 'required-label',
  },
  {
    label: '单位介绍',
    key: 'companyIntroduce',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const targetIndexTableProps = ref([
  {
    label: '①现状总建筑面积（m²）',
    key: 'beforeTotalArea',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '②拟保留和改造建筑面积（m²）',
    key: 'beforeReformArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '③拟拆除建筑面积（m²）',
    key: 'beforeDismantleArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '④更新后总建筑面积（m²）',
    key: 'afterTotalArea',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '⑤拟保留和改造建筑面积（m²）',
    key: 'afterReformArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '⑥改造中增加建筑面积（m²）',
    key: 'afterDismantle',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '⑦新增建筑面积（m²）',
    key: 'afterBuildingArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
])

const targetIndexTableProps2 = ref([
  {
    label: '拆除比例（%）',
    key: 'beforeRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '拆建比例（%）',
    key: 'afterRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
])

const targetIndexTableProps3 = ref([
  {
    label: '拆除比例（%）',
    key: 'regionBeforeRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: false,
  },
  {
    label: '拆建比例（%）',
    key: 'regionAfterRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: false,
  },
])

const fundingSourceTableProps = ref([
  {
    label: '本级政府预算（万元）',
    key: 'govBudget',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '上级财政补助（万元）',
    key: 'financeBudget',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '企业自筹（万元）',
    key: 'companyPrepare',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '银行贷款（万元）',
    key: 'bankLoans',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '其他金融投资（万元）',
    key: 'financeInvest',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '居民出资（万元）',
    key: 'jmcz',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '其他渠道（万元）',
    key: 'otherChannels',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
])

const fundingSourceTableProps2 = ref([
  {
    label: '合计：计划总投资（亿元）',
    key: 'totalInvest',
    renderType: 'input',
    disabled: true,
  },
])

const handleInvestmentCalc = (formData) => {
  let sum = 0
  Object.keys(formData).forEach((key) => {
    sum += getNumber(formData[key])
  })
  vm?.proxy.$refs.infoRef11?.inputData({ totalInvest: sum / 10000 })
}

const projectCoverTableProps = ref([
  {
    label: '是否涵盖老旧小区改造项目',
    key: 'isOldVillageReform',
    renderType: 'radio',
    control: true,
    options: [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' },
    ],
  },
  {
    label: '老旧小区改造建筑面积（m²）',
    key: 'villageReformArea1',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '项目计划总投资（万元）',
    key: 'peTotalInvest1',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '是否涵盖城中村改造项目',
    key: 'isNewVillageReform',
    renderType: 'radio',
    control: true,
    options: [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' },
    ],
  },
  {
    label: '城中村改造建筑面积（m²）',
    key: 'villageReformArea2',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '项目计划总投资（万元）',
    key: 'peTotalInvest2',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
])

const planningAdjustmentTableProps = ref([
  {
    label: '是否涉及控规调整',
    key: 'isAdjust',
    renderType: 'radio',
    control: true,
    options: [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' },
    ],
  },
  {
    label: '调整指标（可多选）',
    key: 'adjustIndicators',
    renderType: 'checkbox',
    calc: true,
    disabled: true,
    options: [
      {
        label: '容积率',
        value: '01',
      },
      {
        label: '高度密集强度',
        value: '02',
      },
      {
        label: '绿地率',
        value: '03',
      },
      {
        label: '用地性质',
        value: '04',
      },
      {
        label: '其他',
        value: '10',
        input: true,
        otherKey: 'other4',
      },
    ],
  },
])

const handleChangeProjectCoverRadio = (key, value) => {
  const index = projectCoverTableProps.value.findIndex(
    (item) => item.key === key
  )
  const nextItem = projectCoverTableProps.value[index + 1]
  const nextItem2 = projectCoverTableProps.value[index + 2]
  nextItem.disabled = value === 'N'
  nextItem2.disabled = value === 'N'
  if (value === 'N') {
    vm?.proxy.$refs.infoRef12?.inputData({
      [nextItem.key]: '',
      [nextItem2.key]: '',
    })
  }
}

const handleChangePlanningAdjustmentRadio = (key, value) => {
  const index = planningAdjustmentTableProps.value.findIndex(
    (item) => item.key === key
  )
  planningAdjustmentTableProps.value[index + 1].disabled = value === 'N'
  if (value === 'N') {
    vm?.proxy.$refs.infoRef13?.inputData({
      adjustIndicators: [],
      other4: '',
    })
  }
}

const houseDemolitionTableProps = ref([
  {
    label: '是否涉及房屋征拆',
    key: 'isDemolition',
    renderType: 'radio',
    control: true,
    options: [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' },
    ],
  },
  {
    label: '征迁方式（可多选）',
    key: 'relocationMode',
    renderType: 'checkbox',
    calc: true,
    disabled: true,
    options: [
      {
        label: '政府征收',
        value: '01',
      },
      {
        label: '协议搬迁',
        value: '02',
      },
      {
        label: '其他',
        value: '10',
        input: true,
        otherKey: 'other5',
      },
    ],
  },
  {
    label: '安置方式（可多选）',
    key: 'placeMode',
    disabled: true,
    renderType: 'checkbox',
    calc: true,
    options: [
      {
        label: '就地实物安置',
        value: '01',
      },
      {
        label: '异地实物安置',
        value: '02',
      },
      {
        label: '货币安置',
        value: '03',
      },
      {
        label: '其他',
        value: '10',
        input: true,
        otherKey: 'other6',
      },
    ],
  },
])

const handleChangeHouseDemolitionRadio = (key, value) => {
  const index = houseDemolitionTableProps.value.findIndex(
    (item) => item.key === key
  )
  houseDemolitionTableProps.value[index + 1].disabled = value === 'N'
  houseDemolitionTableProps.value[index + 2].disabled = value === 'N'
  if (value === 'N') {
    vm?.proxy.$refs.infoRef14?.inputData({
      relocationMode: [],
      placeMode: [],
      other5: '',
      other6: '',
    })
  }
}

const landSupplyTableProps = ref([
  {
    label: '是否涉及土地供应',
    key: 'isSupply',
    control: true,
    renderType: 'radio',
    options: [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' },
    ],
  },
  {
    label: '供应方式（可多选）',
    key: 'supplyMode',
    disabled: true,
    renderType: 'checkbox',
    calc: true,
    options: [
      {
        label: '行政划拨',
        value: '01',
      },
      {
        label: '协议出让',
        value: '02',
      },
      {
        label: '带实施方案招拍挂',
        value: '03',
      },
      {
        label: '其他',
        value: '10',
        input: true,
        otherKey: 'other7',
      },
    ],
  },
])

const handleChangeLandSupplyRadio = (key, value) => {
  const index = landSupplyTableProps.value.findIndex((item) => item.key === key)
  landSupplyTableProps.value[index + 1].disabled = value === 'N'
  if (value === 'N') {
    vm?.proxy.$refs.infoRef15?.inputData({
      supplyMode: [],
      other7: '',
    })
  }
}

const historicalResourceBaseProps = ref([
  {
    label: '国家文保单位',
    key: 'national',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '省级文保单位',
    key: 'province',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '市级文保单位',
    key: 'city',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '区级文保单位',
    key: 'district3',
    renderType: 'render',
    disabled: true,
  },
])

const historicalResourceBaseProps2 = ref([
  {
    label: '历史建筑',
    key: 'historical',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '传统风貌建筑',
    key: 'traditional',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '保护措施',
    key: 'resourcesSafeguard',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const historicalResourceTableProps = ref([
  {
    label: '数量（处）',
    key: 'number',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '面积（m²）',
    key: 'area',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const historicalResourceTableProps2 = ref([
  {
    label: '数量（栋）',
    key: 'number',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '面积（m²）',
    key: 'area',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const ancientTreeBaseProps = ref([
  {
    label: '国家一级古树',
    key: 'levelOne',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '国家二级古树',
    key: 'levelTwo',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '国家三级古树',
    key: 'levelThree',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '名木',
    key: 'famousTree',
    renderType: 'render',
    disabled: true,
  },
  {
    label: '保护措施',
    key: 'treeSafeguard',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const ancientTreeTableProps = ref([
  {
    label: '数量（棵）',
    key: 'number',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const tableData = ref([])

const implementationPlanTableProps = ref([
  {
    label: '年份',
    key: 'year',
    renderType: 'year',
  },
  {
    label: '实施内容',
    key: 'executeContent',
    renderType: 'input',
    placeholder: '请输入',
  },
  {
    label: '年度投资（万元）',
    key: 'ndtz',
    renderType: 'input',
    placeholder: '请输入',
  },
])

const handleAddTableData = () => {
  tableData.value.push({
    year: '',
    executeContent: '',
    ndtz: '',
  })
}

const handleRemoveClick = (index: number) => {
  tableData.value.splice(index, 1)
}

const getSubmitData = () => {
  let obj = {}
  for (let i = 1; i < 16; i++) {
    const data = vm?.proxy.$refs[`infoRef${i}`]?.getFilledFormData() || {}
    Object.assign(obj, data)
  }
  const resourceList = []
  historicalResourceBaseProps.value.forEach((item, index) => {
    if (item.disabled) return
    const data = vm?.proxy.$refs?.infoRef16[index]?.getFilledFormData() || {}
    resourceList.push({
      ...data,
      type: '0' + (index + 1),
    })
  })
  historicalResourceBaseProps2.value.forEach((item, index) => {
    if (item.disabled) return
    if (item.key === 'resourcesSafeguard') return
    const data = vm?.proxy.$refs?.infoRef17[index]?.getFilledFormData() || {}
    resourceList.push({
      ...data,
      type: '0' + (index + 5),
    })
  })
  ancientTreeBaseProps.value.forEach((item, index) => {
    if (item.disabled) return
    if (item.key === 'treeSafeguard') return
    const data = vm?.proxy.$refs?.infoRef18[index]?.getFilledFormData() || {}
    resourceList.push({
      ...data,
      type: '0' + (index + 7),
    })
  })
  obj = {
    ...obj,
    ...form,
    peType: obj.peType.join(';'),
    operateMode: obj.operateMode.join(';'),
    adjustIndicators: obj.adjustIndicators.join(';'),
    relocationMode: obj.relocationMode.join(';'),
    placeMode: obj.placeMode.join(';'),
    supplyMode: obj.supplyMode.join(';'),
    plProjectPlanList: tableData.value,
    district: regionId.value,
    street: streetId.value.toString(),
    plProjectResouceList: resourceList,
    fileRelList: form.fileRelList.filter((item) => item.fileId),
  }
  return obj
}

const handleChangeCheck = (item) => {
  item.disabled = !form[item.key]
}

const drawRegionVisible = ref(false)
const drawRegionDisabled = ref(false)
const mapType = 'draw'
const handleChangeArea = (data) => {
  drawRegionVisible.value = false
  const obj = {
    ...data,
  }
  obj.position = data.wgsPosition
  obj.linePosition = data.lineWgsPosition
  obj.pointPosition = data.pointWgsPosition
  Object.assign(form, obj)
}

const handleDrawRegion = () => {
  drawRegionVisible.value = true
}

const formKeys = [
  'id',
  'shgn1',
  'shgn2',
  'stgn1',
  'stgn2',
  'cygn1',
  'cygn2',
  'whgn1',
  'whgn2',
  'aqgn1',
  'aqgn2',
  'jtgn1',
  'jtgn2',
  'other2',
  'other3',
  'national',
  'province',
  'city',
  'district3',
  'historical',
  'traditional',
  'levelOne',
  'levelTwo',
  'levelThree',
  'famousTree',
  'treeSafeguard',
  'resourcesSafeguard',
  'position',
  'wgsPosition',
  'linePosition',
  'lineWgsPosition',
  'pointPosition',
  'pointWgsPosition',
]

onBeforeMount(() => {
  formKeys.forEach((key) => {
    vm?.proxy.$set(form, key, '')
  })
})

const emit = defineEmits(['changeAreaId'])

onMounted(async () => {
  await getAreaInfo()
  getAreaProjectOptions()
  if (!props.pkid) return
  getProjectInventoryDetail(props.pkid).then((res) => {
    if (res.success) {
      const data = res.data
      emit('changeAreaId', data.regionId)
      const temp = {
        wgsPosition: data.position,
        lineWgsPosition: data.linePosition,
        pointWgsPosition: data.pointPosition,
      }
      Object.assign(data, temp)
      formKeys.forEach((key) => {
        form[key] = data[key] ?? ''
      })
      form.fileRelList = data.fileRelList?.map((item) => {
        return {
          ...item,
          name: item.fileName,
          url: baseFileUrl + item.filePath,
        }
      })
      const obj = {
        peType: data.peType?.split(';') || [],
        operateMode: data.operateMode?.split(';') || [],
        adjustIndicators: data.adjustIndicators?.split(';') || [],
        relocationMode: data.relocationMode?.split(';') || [],
        placeMode: data.placeMode?.split(';') || [],
        supplyMode: data.supplyMode?.split(';') || [],
      }
      Object.assign(data, obj)
      tableData.value = data.plProjectPlanList || []
      regionId.value = data.district || ''
      const resourceList = data.plProjectResouceList || []
      for (let i = 1; i < 16; i++) {
        vm?.proxy.$refs[`infoRef${i}`]?.inputData(data)
      }
      resourceList.forEach((resource) => {
        if (!resource.type) return
        const type = +resource.type.replace('0', '')
        if (type < 5) {
          const index = type - 1
          vm?.proxy.$refs?.infoRef16[index]?.inputData(resource)
          const item = historicalResourceBaseProps.value[index]
          item.disabled = false
          form[item.key] = true
        } else if (type < 7) {
          const index = type - 5
          vm?.proxy.$refs?.infoRef17[index]?.inputData(resource)
          const item = historicalResourceBaseProps2.value[index]
          item.disabled = false
          form[item.key] = true
        } else {
          const index = type - 7
          vm?.proxy.$refs?.infoRef18[index]?.inputData(resource)
          const item = ancientTreeBaseProps.value[index]
          item.disabled = false
          form[item.key] = true
        }
      })
      projectCoverTableProps.value[1].disabled = data.isOldVillageReform === 'N'
      projectCoverTableProps.value[2].disabled = data.isOldVillageReform === 'N'
      projectCoverTableProps.value[4].disabled = data.isNewVillageReform === 'N'
      projectCoverTableProps.value[5].disabled = data.isNewVillageReform === 'N'
      planningAdjustmentTableProps.value[1].disabled = data.isAdjust === 'N'
      houseDemolitionTableProps.value[1].disabled = data.isDemolition === 'N'
      houseDemolitionTableProps.value[2].disabled = data.isDemolition === 'N'
      landSupplyTableProps.value[1].disabled = data.isSupply === 'N'
      nextTick(() => {
        streetId.value = data.street?.split(',') || []
      })
    } else {
      Message.error(res.message)
    }
  })
})

const inputData = (data) => {
  emit('changeAreaId', data.regionId)
  const temp = {
    wgsPosition: data.position,
    lineWgsPosition: data.linePosition,
    pointWgsPosition: data.pointPosition,
  }
  Object.assign(data, temp)
  formKeys.forEach((key) => {
    form[key] = data[key] ?? ''
  })
  form.fileRelList = data.fileRelList?.map((item) => {
    return {
      ...item,
      name: item.fileName,
      url: baseFileUrl + item.filePath,
    }
  })
  const obj = {
    peType: data.peType?.split(';') || [],
    operateMode: data.operateMode?.split(';') || [],
    adjustIndicators: data.adjustIndicators?.split(';') || [],
    relocationMode: data.relocationMode?.split(';') || [],
    placeMode: data.placeMode?.split(';') || [],
    supplyMode: data.supplyMode?.split(';') || [],
  }
  Object.assign(data, obj)
  tableData.value = data.plProjectPlanList || []
  regionId.value = data.district || ''
  const resourceList = data.plProjectResouceList || []
  for (let i = 1; i < 16; i++) {
    vm?.proxy.$refs[`infoRef${i}`]?.inputData(data)
  }
  resourceList.forEach((resource) => {
    if (!resource.type) return
    const type = +resource.type.replace('0', '')
    if (type < 5) {
      const index = type - 1
      vm?.proxy.$refs?.infoRef16[index]?.inputData(resource)
      const item = historicalResourceBaseProps.value[index]
      item.disabled = false
      form[item.key] = true
    } else if (type < 7) {
      const index = type - 5
      vm?.proxy.$refs?.infoRef17[index]?.inputData(resource)
      const item = historicalResourceBaseProps2.value[index]
      item.disabled = false
      form[item.key] = true
    } else {
      const index = type - 7
      vm?.proxy.$refs?.infoRef18[index]?.inputData(resource)
      const item = ancientTreeBaseProps.value[index]
      item.disabled = false
      form[item.key] = true
    }
  })
  projectCoverTableProps.value[1].disabled = data.isOldVillageReform === 'N'
  projectCoverTableProps.value[2].disabled = data.isOldVillageReform === 'N'
  projectCoverTableProps.value[4].disabled = data.isNewVillageReform === 'N'
  projectCoverTableProps.value[5].disabled = data.isNewVillageReform === 'N'
  planningAdjustmentTableProps.value[1].disabled = data.isAdjust === 'N'
  houseDemolitionTableProps.value[1].disabled = data.isDemolition === 'N'
  houseDemolitionTableProps.value[2].disabled = data.isDemolition === 'N'
  landSupplyTableProps.value[1].disabled = data.isSupply === 'N'
  nextTick(() => {
    streetId.value = data.street?.split(',') || []
  })
}

const getNumber = (str: string) => {
  return Number(str) || 0
}

const handleCalcNum = (formData: any) => {
  // console.log(formData)

  const beforeDismantleArea = getNumber(formData['beforeDismantleArea'])
  const beforeTotalArea =
    getNumber(formData['beforeReformArea']) + beforeDismantleArea

  const beforeRatio = beforeTotalArea
    ? beforeDismantleArea / beforeTotalArea
    : 0

  const afterTotalArea =
    getNumber(formData['afterReformArea']) +
    getNumber(formData['afterBuildingArea']) +
    getNumber(formData['afterDismantle'])

  const afterRatio = beforeDismantleArea
    ? (getNumber(formData['afterBuildingArea']) +
        getNumber(formData['afterDismantle'])) /
      beforeDismantleArea
    : 0

  const infoRef7 = vm?.proxy.$refs.infoRef7
  const infoRef8 = vm?.proxy.$refs.infoRef8

  infoRef7.inputData({
    beforeTotalArea,
    afterTotalArea,
  })
  infoRef8.inputData({
    beforeRatio: (beforeRatio * 100).toFixed(2),
    afterRatio: (afterRatio * 100).toFixed(2),
  })
}

const handleChangeSelect = (key, val) => {
  if (key === 'regionId') {
    if (val) {
      targetIndexTableProps3.value.map((item) => {
        item.disabled = true
      })
    } else {
      targetIndexTableProps3.value.map((item) => {
        item.disabled = false
      })
    }
    const f = areaProjectOptions.value.find((item) => item.value === val)
    let obj = {
      regionBeforeRatio: '',
      regionAfterRatio: '',
    }
    if (f) {
      obj = {
        regionBeforeRatio: f.regionBeforeRatio ?? '',
        regionAfterRatio: f.regionAfterRatio ?? '',
      }
    }
    vm?.proxy.$refs.infoRef9?.inputData(obj)
  }
}

const handleChangeFile = async (file, fileList) => {
  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    formData.append('type', 'projectShp')
    const res = await uploadFile(formData)
    if (res.success) {
      file.fileId = res.data
    } else {
      Message.error(res.message)
    }
  } catch (e) {
    Message.error('上传失败')
  }
  form.fileRelList = fileList
}

const handleRemove = (file, fileList) => {
  form.fileRelList = fileList
}

const handlePreview = (file) => {
  const url = file.url
  window.open(url)
}

defineExpose({
  inputData,
  getSubmitData,
})
</script>

<template>
  <el-form class="detail-table" :disabled="disabled">
    <common-base-info-table
      ref="infoRef1"
      :base-info-table-props="projectBasePart"
      :border="true"
      :column="2"
      class="cell-num-2"
      @changeSelect="handleChangeSelect"
    >
    </common-base-info-table>
    <common-base-info-table
      ref="infoRef2"
      :base-info-table-props="projectBasePart2"
      :border="true"
      :column="1"
      class="cell-num-1"
    >
      <template #locationRange>
        <common-base-info-table
          ref="infoRef3"
          :column="7"
          :border="true"
          :base-info-table-props="locationRangeTableProps"
          :direction="'vertical'"
        >
          <template #district>
            <template v-if="userLevel === 0 || userLevel === 5">
              <el-select v-model="regionId" placeholder="待选择">
                <el-option
                  v-for="item in regionList"
                  :key="item.pkid"
                  :label="item.areaName"
                  :value="item.pkid"
                ></el-option>
              </el-select>
            </template>
            <template v-else> {{ getRegionName(regionId) }} </template>
          </template>
          <template #street>
            <template
              v-if="userLevel === 0 || userLevel === 5 || userLevel === 2"
            >
              <el-select v-model="streetId" placeholder="请选择" multiple>
                <el-option
                  v-for="item in streetList"
                  :key="item.pkid"
                  :label="item.areaName"
                  :value="item.pkid"
                ></el-option>
              </el-select>
            </template>
            <template v-else>
              {{ getStreetName(streetId) }}
            </template>
          </template>
        </common-base-info-table>
      </template>
      <template #owner>
        <common-base-info-table
          ref="infoRef4"
          :column="1"
          :base-info-table-props="ownerTableProps"
          :border="true"
          class="cell-num-1-inner"
        />
      </template>
    </common-base-info-table>
    <common-base-info-table
      ref="infoRef5"
      :base-info-table-props="projectBasePart3"
      :border="true"
      :column="2"
      class="cell-num-2"
    >
    </common-base-info-table>
    <common-base-info-table
      ref="infoRef6"
      :base-info-table-props="projectBasePart4"
      :border="true"
      :column="1"
      class="cell-num-1-last"
    >
      <template #latitude>
        <div class="table-inline-item">
          <div class="table-property">针对现状及问题分析诊断</div>
          <div class="table-property">主要更新措施</div>
        </div>
      </template>
      <template #lifeFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.shgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.shgn2"></el-input>
          </div>
        </div>
      </template>
      <template #ecologicalFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.stgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.stgn2"></el-input>
          </div>
        </div>
      </template>
      <template #industryFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.cygn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.cygn2"></el-input>
          </div>
        </div>
      </template>
      <template #cultureFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.whgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.whgn2"></el-input>
          </div>
        </div>
      </template>
      <template #securityFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.aqgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.aqgn2"></el-input>
          </div>
        </div>
      </template>
      <template #trafficFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.jtgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.jtgn2"></el-input>
          </div>
        </div>
      </template>
      <template #other>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.other2"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.other3"></el-input>
          </div>
        </div>
      </template>
      <template #targetIndex>
        <div class="target-index-content">
          <div class="table-inline-item">
            <div class="table-property">现状建筑面积指标</div>
            <div class="table-property">更新后建筑面积指标</div>
          </div>
          <common-base-info-table
            ref="infoRef7"
            :column="7"
            :border="true"
            :base-info-table-props="targetIndexTableProps"
            :direction="'vertical'"
            class="cell-num-7"
            @calcNum="handleCalcNum"
          />
          <common-base-info-table
            ref="infoRef8"
            :column="2"
            :border="true"
            :base-info-table-props="targetIndexTableProps2"
            class="cell-num-2-inner"
          />
        </div>
      </template>
      <template #areaTargetIndex>
        <common-base-info-table
          ref="infoRef9"
          :column="2"
          :border="true"
          :base-info-table-props="targetIndexTableProps3"
          class="cell-num-2-inner"
        />
      </template>
      <template #fundingSource>
        <common-base-info-table
          ref="infoRef10"
          :column="7"
          :border="true"
          :base-info-table-props="fundingSourceTableProps"
          :direction="'vertical'"
          class="cell-num-7"
          @calcNum="handleInvestmentCalc"
        />
        <common-base-info-table
          ref="infoRef11"
          :column="1"
          :border="true"
          :base-info-table-props="fundingSourceTableProps2"
          class="cell-num-1-inner"
        />
      </template>
      <template #projectCover>
        <common-base-info-table
          ref="infoRef12"
          :column="3"
          :border="true"
          :base-info-table-props="projectCoverTableProps"
          class="cell-num-3"
          @changeRadio="handleChangeProjectCoverRadio"
        />
      </template>
      <template #planningAdjustment>
        <common-base-info-table
          ref="infoRef13"
          :column="1"
          :border="true"
          :base-info-table-props="planningAdjustmentTableProps"
          class="cell-num-1-inner"
          @changeRadio="handleChangePlanningAdjustmentRadio"
        />
      </template>
      <template #houseDemolition>
        <common-base-info-table
          ref="infoRef14"
          :column="1"
          :border="true"
          :base-info-table-props="houseDemolitionTableProps"
          class="cell-num-1-inner"
          @changeRadio="handleChangeHouseDemolitionRadio"
        />
      </template>
      <template #landSupply>
        <common-base-info-table
          ref="infoRef15"
          :column="1"
          :border="true"
          :base-info-table-props="landSupplyTableProps"
          class="cell-num-1-inner"
          @changeRadio="handleChangeLandSupplyRadio"
        />
      </template>
      <template #historicalResource>
        <el-descriptions
          :column="1"
          border
          class="cell-num-1-inner"
          content-class-name="no-padding-content"
        >
          <el-descriptions-item
            v-for="(item, index) in historicalResourceBaseProps"
            :key="index"
            :label="item.label"
          >
            <template slot="label" v-if="item.renderType === 'render'">
              <el-checkbox
                v-model="form[item.key]"
                @change="handleChangeCheck(item)"
                >{{ item.label }}</el-checkbox
              >
            </template>
            <template slot="default" v-if="item.renderType === 'render'">
              <common-base-info-table
                ref="infoRef16"
                :column="2"
                :border="true"
                :base-info-table-props="historicalResourceTableProps"
                class="cell-num-2"
                :disabled="item.disabled"
              />
            </template>
            <template slot="default" v-else>
              <el-input
                v-model="form[item.key]"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-descriptions-item>
          <el-descriptions-item
            v-for="(item, index) in historicalResourceBaseProps2"
            :key="index"
            :label="item.label"
          >
            <template slot="label" v-if="item.renderType === 'render'">
              <el-checkbox
                v-model="form[item.key]"
                @change="handleChangeCheck(item)"
                >{{ item.label }}</el-checkbox
              >
            </template>
            <template slot="default" v-if="item.renderType === 'render'">
              <common-base-info-table
                ref="infoRef17"
                :column="2"
                :border="true"
                :base-info-table-props="historicalResourceTableProps2"
                class="cell-num-2"
                :disabled="item.disabled"
              />
            </template>
            <template slot="default" v-else>
              <el-input
                v-model="form[item.key]"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <template #ancientTree>
        <el-descriptions
          :column="1"
          border
          class="cell-num-1-inner"
          content-class-name="no-padding-content"
        >
          <el-descriptions-item
            v-for="(item, index) in ancientTreeBaseProps"
            :key="index"
            :label="item.label"
          >
            <template slot="label" v-if="item.renderType === 'render'">
              <el-checkbox
                v-model="form[item.key]"
                @change="handleChangeCheck(item)"
                >{{ item.label }}</el-checkbox
              >
            </template>
            <template slot="default" v-if="item.renderType === 'render'">
              <common-base-info-table
                ref="infoRef18"
                :column="1"
                :border="true"
                :base-info-table-props="ancientTreeTableProps"
                class="cell-num-1-inner"
                :disabled="item.disabled"
              />
            </template>
            <template slot="default" v-else>
              <el-input
                v-model="form[item.key]"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <template #projectVector>
        <div class="project-vector-content">
          <div class="table-inline-item">
            1.行政区范围；2.片区范围；3.项目范围。（shp格式，2000国家大地坐标系）
          </div>
          <el-form>
            <div class="table-inline-item shp-upload">
              <div class="table-content-item">
                <el-upload
                  :auto-upload="false"
                  class="upload-demo"
                  action=""
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-change="handleChangeFile"
                  multiple
                  :limit="6"
                  :file-list="form.fileRelList"
                >
                  <el-button size="small" type="primary">上传范围</el-button>
                </el-upload>
              </div>
              <div class="table-content-item">
                <el-button type="primary" @click="handleDrawRegion"
                  >{{
                    `点击定位/绘制${
                      form.position || form.linePosition || form.pointPosition
                        ? '(已绘制)'
                        : ''
                    }`
                  }}
                </el-button>
              </div>
            </div>
          </el-form>
        </div>
      </template>
      <template #implementationPlan>
        <el-table :data="tableData">
          <el-table-column
            v-for="item in implementationPlanTableProps"
            :key="item.label"
            :label="item.label"
          >
            <template #default="{ row }" v-if="item.renderType === 'input'">
              <el-input v-model="row[item.key]" placeholder="请输入"></el-input>
            </template>
            <template #default="{ row }" v-else-if="item.renderType === 'year'">
              <el-date-picker
                v-model="row[item.key]"
                type="year"
                placeholder="选择年份"
                value-format="yyyy"
                format="yyyy"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot="header">
              <el-button type="text" @click="handleAddTableData">
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px"
                ></i>
              </el-button>
            </template>
            <template v-slot="scope">
              <el-button type="text" @click="handleRemoveClick(scope.$index)">
                <i
                  style="color: #f78989; font-size: 18px"
                  class="el-icon-delete"
                  :key="scope.$index"
                ></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </common-base-info-table>

    <draw-map
      title="范围绘制"
      :visible="drawRegionVisible"
      :data="form"
      :map-type="mapType"
      :disabled="props.disabled"
      @update="handleChangeArea"
      @close="drawRegionVisible = false"
      map-id="one-map-draw6"
    />
  </el-form>
</template>

<style scoped lang="scss">
.detail-table {
  width: 100%;

  $base-cell-width: calc(100% / 8);

  .name-inline {
    display: flex;
    align-items: center;

    .el-input {
      width: 220px;
      margin-right: 12px;
    }
  }

  .cell-num-1 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }
    }
  }

  .cell-num-1-last {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 7;
      }
    }
  }

  .cell-num-2 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 3;
      }
    }
  }

  .cell-num-3 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width;
      }

      .el-descriptions-item__content:nth-child(2) {
        width: $base-cell-width * 2;
      }
    }
  }

  :deep(.no-padding-content) {
    padding: 0 !important;
  }

  .target-index-content {
    width: 100%;
  }
  .cell-num-7 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width;
      }
    }
  }

  .cell-num-1-inner {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width * 1.15;
      }
    }
  }

  .cell-num-2-inner {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width * 1;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 2.5;
      }
    }
  }
  .table-inline-item {
    height: 46px;
    display: flex;
    align-items: center;

    &.shp-upload {
      height: inherit;
    }

    div:first-child {
      border-right: 1px solid #ebeef5;
    }
  }

  .table-property {
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .table-content-item {
    box-sizing: border-box;
    padding: 10px;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .project-vector-content {
    .table-inline-item:first-child {
      margin-left: 15px;
      border-bottom: 1px solid #ebeef5;
    }

    .table-inline-item:last-child {
      .el-button {
        height: 32px;
        display: flex;
        padding-top: 0;
        padding-bottom: 0;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
